export class SSEClient {
  constructor(url, options = {}) {
    this.url = import.meta.env.VITE_BASE_API + url;
    this.options = options;
    this.eventSource = null;
    this.callbacks = {};
    this.init()
  }

  // 初始化 EventSource 连接
  init() {
    if (this.eventSource) {
      this.close(); // 关闭已有的连接
    }

    this.eventSource = new EventSource(this.url, this.options);

    // 连接成功时触发
    this.eventSource.onopen = (event) => {
      console.log("连接已建立", event);
    };

    // 连接失败时触发
    this.eventSource.onerror = (error) => {
      console.error("EventSource 失败:", error);
      this.close(); // 出现错误时关闭连接
    };
  }

  // 添加事件监听器
  on(event, callback) {
    if (!this.callbacks[event]) {
      this.callbacks[event] = [];
    }
    this.callbacks[event].push(callback);

    if (this.eventSource) {
      this.eventSource.addEventListener(event, (e) => {
        this.callbacks[event].forEach((cb) => cb(e));
      });
    }
  }

  // 移除事件监听器
  off(event, callback) {
    if (this.callbacks[event]) {
      this.callbacks[event] = this.callbacks[event].filter(
        (cb) => cb !== callback
      );
    }
  }

  close() {
    if (this.eventSource) {
      this.eventSource.close();
      console.log("连接已关闭.");
    }
  }

}
